<template>
  <div id="log">
    <el-form
      class="app"
      ref="elForm"
      :model="user"
      :rules="rules"
      size="medium"
      label-width="100px"
    >
      <div class="title-container">
        <h3 class="title">
          <img src="../assets/bt.png" alt="" />
        </h3>
      </div>
      <el-form-item label="手机号：" prop="phone">
        <el-input
          v-model="user.phone"
          placeholder="请输入手机号"
          clearable
          :style="{ width: '100%' }"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input
          v-model="user.password"
          placeholder="请输入密码"
          clearable
          show-password
          :style="{ width: '100%' }"
        ></el-input>
      </el-form-item>
      <el-form-item size="large">
        <el-button class="tj" type="primary" @click="submitForm"
          >登 录</el-button
        >
        <el-button class="cz" @click="resetForm">重 置</el-button>
        <el-link @click="$router.push('/register')">没有账号？点击这里</el-link>
      </el-form-item>
    </el-form>
    <!-- 人脸对话框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="40%">
      <div class="videodome">
        <div>
          <video
            id="videoCamera"
            width="250"
            height="250"
            autoplay
            style="border-radius: 180px; box-shadow: darkgrey 0 0 30px 5px"
          ></video>
        </div>
        <canvas
          style="display: none"
          id="canvasCamera"
          width="250"
          height="250"
        ></canvas>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="success" @click="setImage()">登录</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { login, facelogin } from "@/axios/user";
import { mapMutations } from "vuex";
export default {
  name: "login",
  components: {},
  props: [],
  data() {
    return {
      videoWidth: 250,
      videoHeight: 250,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      imga: "",
      dialogVisible: false,
      user: {
        phone: undefined,
        password: undefined,
      },
      rules: {
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
      },
      userList: [],
      branchId: [],
      branchlist: [],
      breachs: [],
    };
  },
  watch: {
    dialogVisible(){
      if(!this.dialogVisible){
        this.openFullScreen1()
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    ...mapMutations(["getuser"]),
    submitForm() {
      this.$refs["elForm"].validate(async (valid) => {
        if (!valid) return;
        let { data } = await login(this.user);
        if (data.code != 200) {
          this.$message.error("登录失败！");
          return;
        }
        if (data.id) {
          window.sessionStorage.setItem("id", data.id.id);
          this.dialogVisible = true;
          this.$nextTick(() => {
            this.getCompetence();
          });
        } else {
          this.getuser(data.user);
          window.sessionStorage.setItem("token", data.token);
          this.$router.replace("/");
        }
      });
    },
    resetForm() {
      this.$refs["elForm"].resetFields();
    },
    // 打开摄像头
    getCompetence() {
      var _this = this;
      this.thisCancas = document.getElementById("canvasCamera");
      this.thisContext = this.thisCancas.getContext("2d");
      this.thisVideo = document.getElementById("videoCamera");
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play();
          };
        })
        .catch((err) => {});
    },
    // 拍照
    async setImage() {
      this.imgif = true;
      var _this = this;
      // 点击，canvas画图
      _this.thisContext.drawImage(_this.thisVideo, 0, 0, 250, 250);

      // 获取图片base64链接
      var image = this.thisCancas.toDataURL("image/png");
      let id = window.sessionStorage.getItem("id");
      let dataA = { id: id, face: image };
      let { data } = await facelogin(dataA);
      if (data.code != 200) {
        this.$message.error("人脸不匹配");
        return;
      }
      this.openFullScreen1();
      this.getuser(data.user);
      window.sessionStorage.setItem("token", data.token);
      this.$router.replace("/");
    },
    //关闭摄像头并上传数据
    openFullScreen1() {
      // let face = window.sessionStorage.getItem("img");
      // if (!face) {
      //   this.$message.info("尚未拍照！");
      //   this.dialogVisible = false;
      //   return;
      // }
      this.thisVideo.srcObject.getTracks()[0].stop(), //关闭摄像头
        setTimeout(async () => {
          this.dialogVisible = false;
        }, 2000);
    },
  },
};
</script>
<style lang="scss" scoped>
#log {
  width: 100%;
  height: 100%;
  background-image: url("../assets/bj.jpg");
  background-size: 100%;
}
.app {
  width: 400px;
  height: 250px;
  padding: 40px 50px 20px 20px;
  background-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  border-radius: 5px;
}
::v-deep(label) {
  color: #3262c2 !important;
}
.tj,
.cz {
  border: none;
}
.tj {
  background-color: rgba(35, 84, 127, 0.551);
}
.tj:hover {
  background-color: rgba(0, 17, 255, 0.31);
}
.cz {
  background-color: rgba(240, 255, 255, 0.656);
}
.cz:hover {
  background-color: rgba(15, 171, 171, 0.329);
}
.el-link {
  color: rgb(123, 125, 125) !important;
  margin-left: 12px;
}
.el-link:hover {
  color: rgba(170, 196, 19, 0.582) !important;
}
.title-container,
.title {
  font-size: 10px;
  color: #eee;
  margin: 0 auto 20px;
  text-align: center;
  font-weight: 400;
}
</style>


